//app.js
import md5 from '/utils/md5.js';
var gio = require("utils/gio-minp.js").default;
// version 是你的小程序的版本号, 发版时请调整
gio('init', 'be3128c08891de0b', 'wx4e358e1f2ead4c7b', {
	version: '1.0'
});
var page = {};
let flag = false
App({
	onLaunch: function() {
		// 展示本地存储能力
		var logs = wx.getStorageSync('logs') || []
		logs.unshift(Date.now())
		wx.setStorageSync('logs', logs)
		//判断手机型号

		//查询是否是最新版
		var updateManager = wx.getUpdateManager()
		updateManager.onCheckForUpdate(function(res) {
			// 请求完新版本信息的回调
			console.log(res.hasUpdate)
		})

		updateManager.onUpdateReady(function() {
			wx.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？',
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate()
					}
				}
			})
		})

		updateManager.onUpdateFailed(function() {
			console.log('新版本下载失败')
		})
	},
	request: function(url, params, callBack, method) {
		var header = {
			'content-type': method == 'POST' ? 'application/x-www-form-urlencoded; charset=UTF-8' : 'application/json; charset=utf-8',
			'cookie': wx.getStorageSync("sessionid")
		};
    params.openid = this.isAuth ? wx.getStorageSync("openid") : wx.getStorageSync("openid");
		if(typeof params.sign == 'undefined'){
			params.f_channel = 'xiaochengxu';
			params.sign = this.sign(params);
			// console.log(params,2)
		}
		wx.request({
			url: url,
			header: header,
			data: params,
			method: method ? method : 'GET',
			success: function(res) {
				callBack(res);
			}
		});
	},
  updateFlag: function (e) {
   let that = this
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userInfo']) { //是否已授权用户信息
            console.log('授权用户信息')
            // wx.navigateTo({
            // 	url: that.url
            // });
            that.isAuth = false
            resolve(true)
          } else {
            that.isAuth = true
            resolve(true)
            // let sessionId = wx.getStorageSync("sessionid");
            // let openid = wx.getStorageSync("openid");
            // if (!openid || !sessionId) {
            //   that.loginStep(e)
            // }
          }
        }
      })
    })
  },
  updateRun: function (e) {
    let that = this
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.werun']) { //是否已授权用户信息
            console.log('授权用户信息')
            // wx.navigateTo({
            // 	url: that.url
            // });
            that.isRun = false
            resolve(true)
          } else {
            that.isRun = true
            resolve(true)
            // let sessionId = wx.getStorageSync("sessionid");
            // let openid = wx.getStorageSync("openid");
            // if (!openid || !sessionId) {
            //   that.loginStep(e)
            // }
          }
        }
      })
    })
  },
  isAuth: flag, //是否授权用户信息
  isRun: false,
	userInfo: [],
	skinDomain: 'https://api.yimei.ai/',
	apiDomain: "https://api.160nurse.com/",
	resourceDomain: "https://resource.160nurse.com/",
	wapDomain: "https://m.160nurse.com/",
	sessionid: '',
	address: [],
	sleepPoint: 0,
  skinId: '1', // 打水果皮肤Id
	setWxUserInfo: function(userInfo) {
		//设置本地获取的数据
		this.userInfo = {
			nickname: userInfo.nickName,
			icon: userInfo.avatarUrl,
			cover_img: userInfo.avatarUrl,
			zone_name: userInfo.province + ' ' + userInfo.city
		};
		wx.setStorageSync('nickname', userInfo.nickName);
		wx.setStorageSync('icon', userInfo.avatarUrl);
		wx.setStorageSync('cover_img', userInfo.avatarUrl);
		wx.setStorageSync('zone_name', userInfo.province + ' ' + userInfo.city);
	},
	setApiUserInfo: function(userInfo) {
		//设置接口返回过的数据
		this.userInfo = userInfo;
    console.log('数据', userInfo)
		// console.log(userInfo.user_id,1)
		wx.setStorageSync('user_id', userInfo.user_id);
		wx.setStorageSync('nickname', userInfo.nickname);
		wx.setStorageSync('icon', userInfo.icon);
		wx.setStorageSync('cover_img', userInfo.cover_img);
		wx.setStorageSync('zone_name', userInfo.zone_name);
	},
	setAppUserInfo: function(e) {
		//把数据储存到data
		console.log('把数据储存到data', e)
		var THIS = e;
		let userInfo = {
			user_id: wx.getStorageSync('user_id'),
			nickname: wx.getStorageSync('nickname'),
			icon: wx.getStorageSync('icon'),
			cover_img: wx.getStorageSync('cover_img'),
			zone_name: wx.getStorageSync('zone_name')
		};
		THIS.setData({
			userInfo: userInfo
		});
	},
	onShareAppMessage: function() {
		var nickName = '';
		var userId = 0;
		try {
			nickName = wx.getStorageSync('nickname');
			userId = wx.getStorageSync('user_id');
		} catch (e) {}
    console.log(userId)
		return {
			path: "/pages/index/index?user_id=" + userId,
			title: '每天多走路，除了健康还能换好礼，快来看看吧！',
			imageUrl: this.resourceDomain + 'upload/miniprogram/runstep.png'
		}
	},
	loginStep: function(e) {
		var that = this;
    console.log(e)
    // page = e
		wx.login({
			success(res) {
				if (res.code) {
					wx.request({
						url: that.apiDomain + 'index.php?c=user&a=getopenid',
						data: {
							code: res.code
						},
						success: function(res) {
							console.log('登录成功！')
							var user_info = res.data.data;
							wx.setStorageSync("openid", user_info.openid);
              if (res.data.data.star!= null && !!res.data.data.star.hasOwnProperty('ji')) {
                console.log(111)
                if (!!res.data.data.star.hasOwnProperty('ji_1')) {
                  wx.setStorageSync("isGetChicken", '2')
                } else if (!!res.data.data.star.hasOwnProperty('ji_2')){
                  wx.setStorageSync("isGetChicken", '3')
                } else {
                  wx.setStorageSync("isGetChicken", '1')
                }
                
              } else {
                wx.setStorageSync("isGetChicken", '')
              }
							var openid = user_info.openid;
							var cookie = res.header["Set-Cookie"];
							if (cookie != null) {
								wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
							}
              console.log(user_info, page)
              wx.setStorageSync('sex', user_info.sex)
							that.setApiUserInfo(user_info);
							//把数据写入Data
							that.setAppUserInfo(page)
              that.isAuth = true
							// that.setWxUserInfo(user_info)
							//获取头像名字信息
							that.userstat(page,openid);
							//获取步数
							// that.getRunData(openid, page);
						}
					})
				} else {
					console.log('登录失败！' + res.errMsg)
          return false
				}
			}
		});
	},
	SystemInfo: function(e) {
		var has = e;
		wx.getSystemInfo({
			success(res) {
				console.log(res)
				var s_win = res.screenWidth;
				var s_hie = res.screenHeight;
        console.log(res.model)
        if (res.model.indexOf('iPhone') != -1) {
          has.setData({
            isIphone: true
          })
        } else {
          has.setData({
            isIphone: false
          })
        }
				if (s_win == 375 && s_hie == 812) {
					has.setData({
						iphone_height: 'on',
            iphoneX: 'ix',
            isIphoneX: true
					});
				} else {
          has.setData({
            isIphoneX: false
          })
        };
        if (s_win == 424 && s_hie == 871 && res.model.indexOf('mate20') != -1 || s_hie > 800) {
					has.setData({
						// iphone_height: 'on',
            iphoneX: 'ix'
					});
				}
        if (s_win == 424 && s_hie == 918) {
          has.setData({
            // iphone_height: 'on',
            iphoneX: 'ix',
            huawei: 'hw'
          });
        }

        if (res.model.indexOf('iPhone 6') != -1 || res.model.indexOf('iPhone 5') != -1 || res.model.indexOf('iPhone 4') != -1) {
          has.setData({
            nofind: true
          })
        }

			}
		});
	},
	sign: function(obj) {
		var json = '';
		// var dic={x:2,z:1,y:3};//输出  {x:2，y:3，z:1}
		var sdic = Object.keys(obj).sort();
		// console.log(sdic)
		for (let ki in sdic) {
			json += (sdic[ki] + "=" + encodeURIComponent(obj[sdic[ki]]) + "&");
		}
		// console.log(json + 'key=6723d2909ec9fbf969c000e32ff2f514')
		return md5(json + 'key=6723d2909ec9fbf969c000e32ff2f514')
	},
	/**
	 * 通过判断session是否
	 */
	checkSession: function(e, url, g_id, type, id, u_id, a_id, step, new_url) {
		var that = this;
		var THIS = e;
		page = e;

		var sessionId = wx.getStorageSync("sessionid");
		var openid = wx.getStorageSync("openid");
		var icon = wx.getStorageSync('icon');
		var nickname = wx.getStorageSync('nickname');
		var user_id = wx.getStorageSync('user_id');


		//跳转地址
    that.url = '../mod/null?jump=' + url + '&goods_id=' + g_id + '&type=' + type + '&id=' + id + '&user_id=' +
			u_id + '&activity_id=' + a_id + '&new_url=' + new_url;

		// console.log(this.url,'传送')
		//查询是否授权
		wx.getSetting({
			success(res) {
        let pages = getCurrentPages()
				if (!res.authSetting['scope.userInfo']) { //是否已授权用户信息
					console.log('授权用户信息')
					// wx.navigateTo({
					// 	url: that.url
					// });
          THIS.setData({
            user_auth: true
          })
					return false
				} else if (!res.authSetting['scope.werun']) { //是否已授权步数
          console.log('是首页吗？', pages[pages.length - 1].route.indexOf('index/index'))
          if (pages[pages.length - 1].route.indexOf('index/index') != -1 || pages[pages.length - 1].route.indexOf('play/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index_ix') != -1) {
            console.log('授权步数')
            // return false
            that.getRunData(openid, THIS);
          }
        } else {
          // 运动挑战 定位授权
          let pages = getCurrentPages()
          // if (pages[pages.length - 1].route.indexOf('play/index') != -1) {
          //   if (!res.authSetting['scope.userLocation']) {
          //     wx.authorize({
          //       scope: 'scope.userLocation',
          //       success() {
          //         wx.showToast({ //这里提示失败原因
          //           title: '授权成功！',
          //           duration: 1500
          //         })
          //       },
          //       fail() {
          //         wx.showToast({
          //           title: '您还没有授权位置信息，可能会影响使用体验,可前往个人中心-授权管理开启授权',
          //           icon: 'none'
          //         });
          //       }
          //     })
          //   }
          // }    
					console.log('已查询到有授权')
					if (!sessionId || !openid) {
						console.log("session_key未过期，但Cookie中sessionid不存在，重新登陆");
						that.loginStep(user_id, e);
						return false
					}
          if (pages[pages.length - 1].route.indexOf('index/index') != -1 || pages[pages.length - 1].route.indexOf('play/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index_ix') != -1) {
            that.getRunData(openid, THIS);
          }
					if (!nickname || !icon) {
						// console.log(icon,nickname,'头像')
						wx.navigateTo({
							url: that.url
						});
						return false
					}
					if (step) {
						//获取步数 拆步
						// that.getRunData(openid, THIS);
					}
					//把数据写入Data
					that.setAppUserInfo(THIS)
				};
			}
		});
		
		if(!user_id || !nickname || !icon){
			that.userstat(THIS,openid)
			console.log('已执行获取用户信息')
		}
		

	},
	userstat: function(e, c) { //获取头像名字信息
		var THIS = e;
		var openid = c;
		var that = this;
		that.request(that.apiDomain + 'index.php?c=user&a=userstat', {}, function(res) {
			console.log(res,'获取个人信息')
			if (res.data.status == '1') {
				THIS.setData({
					userInfo: res.data.data
				});
				//储存获取到的数据
				that.setApiUserInfo(res.data.data);
			} else {
				//没登录 重新登录
				that.loginStep(wx.getStorageSync('user_id'), THIS);
			}
		});
	},
	getRunData: function(openid, e) {
		console.log('请求步数', e)
		var that = this;
		var THIS = e;
		wx.login({
			success(res) {
				if (res.code) {
					wx.request({
						url: that.apiDomain + 'index.php?c=user&a=getopenid',
						data: {
							code: res.code
						},
						success: function(res) {
              let openids = res.data.data.openid
              wx.stopPullDownRefresh()
							wx.getWeRunData({
								fail(res) {
                  wx.getSetting({
                    success: function (res) {
                      if (!res.authSetting['scope.werun']) {
                        THIS.setData({
                          rundatabutton: true,
                          run_auth: true
                        });
                      }
                    }
                  })
								},
								success(res) {
									// console.log(res,12)
									console.log('请求步数成功')
                  // 运动挑战 定位授权
                  wx.getSetting({
                    success:function(resd) {
                      let pages = getCurrentPages()
                      if (pages[pages.length - 1].route.indexOf('play/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index_ix') != -1) {
                        if (!resd.authSetting['scope.userLocation']) {
                          wx.authorize({
                            scope: 'scope.userLocation',
                            success() {
                              wx.showToast({ //这里提示失败原因
                                title: '授权成功！',
                                duration: 1500
                              })
                            },
                            fail() {
                              wx.showToast({
                                title: '您还没有授权位置信息，可能会影响使用体验,可前往个人中心-授权管理开启授权',
                                icon: 'none'
                              });
                            }
                          })
                        }
                      }
                    }
                  })    
                  THIS.setData({
                    run_auth: false,
                    userInfo: {
                      icon: wx.getStorageSync('icon')
                    }
                  })
                               
									var encryptedData = res.encryptedData
									wx.request({
										url: that.apiDomain + 'index.php?c=user&a=getTodayStep',
										header: {
											//设置参数内容类型为x-www-form-urlencoded
											'content-type': 'application/x-www-form-urlencoded',
											'Accept': 'application/json'
										},
										data: {
											encryptedData: res.encryptedData,
											iv: res.iv,
                      openid: openids
										},
										method: "POST",
										success: function(res) {
											//判断是否第一次进来
											if (res.data.data.login_num == "0") {
												THIS.setData({
													gif_on: 'on'
												})
												setTimeout(function(e = THIS) {
													e.setData({
														gif_on: ''
													})
												}, 6000);
											}
											/**
											 * 返回今日步数
											 */
											var left_step = res.data.data.step - res.data.data.pointed_step;
											// console.log('执行成功0');
											that.chai_fen(left_step, THIS);
											//计算卡路里
											var t_num = (res.data.data.step / 20);
											var draw_point = res.data.data.draw_point;
											var step = res.data.data.step;
											// console.log(res,'步')
											THIS.setData({
												tiao_num: t_num,
												tiao_ky: (t_num * 0.0065).toFixed(1),
												qian: draw_point ? draw_point : 0,
												todaystep: step ? step : 0
											});
                      // return true
										}
									})
								}
							});
						}
					})
				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		});

	},
	chai_fen: function(left_step, e) {
		var THIS = e;
		// console.log(left_step,'执行成功2')
		//拆分步数
		var num = parseInt(left_step / 100) / 10;
		// console.log(num)
		// var soo = num;
		if (num >= 10) {
			THIS.setData({
				data_num: ['2', '1', '2', '1', '3', '3']
			});
		} else if (num >= 8) {
			THIS.setData({
				data_num: ['1', '2', '1', '2', '1', parseInt((num - 7) * 10) / 10]
			});
		} else if (num >= 6) {
			THIS.setData({
				data_num: ['2', '3', '1', '1', parseInt((num - 5) * 10) / 10]
			});
		} else if (num >= 4) {
			THIS.setData({
				data_num: ['1.2', '0.8', '1', parseInt((num - 3) * 10) / 10]
			});
		} else if (num >= 3) {
			THIS.setData({
				data_num: ['0.4', '1', '0.6', parseInt((num - 2) * 10) / 10]
			});
		} else if (num >= 2) {
			THIS.setData({
				data_num: ['0.7', '0.3', parseInt((num - 1) * 10) / 10]
			});
		} else if (num >= 1) {
			THIS.setData({
				data_num: ['0.5', parseInt((num - 0.5) * 10) / 10]
			});
		} else if (num > 0) {
			THIS.setData({
				data_num: [parseInt(num * 10) / 10]
			});
		};
		// console.log(that.data.data_num)
		//打印出泡泡
	},
	getUserInfo: function(e, options) {
		var that = this;
		var THIS = e;
		wx.getUserInfo({
			lang: "zh_CN",
			fail() {
				console.log('getUserInfo failed');
				setTimeout(function() {
          wx.showToast({
            title: '授权失败，请点击授权',
            icon: "none"
          });
				}, 0);
				// THIS.setData({
				// 	rundatabutton: true
				// });
			},
			success: res => {
        wx.showLoading({
          title: '信息授权中',
        });
				var userInfo = res.userInfo;
				var openid = wx.getStorageSync("openid");
				console.log('信息授权');
				that.request(that.apiDomain + 'index.php?c=user&a=profile', {
					openid: openid,
					nickname: userInfo.nickName,
					gender: userInfo.gender,
					icon: userInfo.avatarUrl,
					invite_user: wx.getStorageSync('invite_user_user_id'),
					zone_name: userInfo.province + ' ' + userInfo.city,
				}, function(res) {
					setTimeout(function() {
						wx.hideLoading()
					}, 2000);
					wx.showToast({
						title: '授权完成,你可以继续操作了',
						icon: "none"
					});
					THIS.setData({
						user_auth: false
					});
          var pages = getCurrentPages()
          // console.log('测试',pages[pages.length - 1].route.indexOf('index/index'))
          if (pages[pages.length - 1].route.indexOf('index/index') != -1) {
            that.checkSession(THIS, '', '', '', '', '', '', '', '')
          }
					if(wx.getStorageSync('invite_user_user_id')){
						console.log('删除缓存邀请id')
						wx.removeStorageSync('invite_user_user_id')
					};
					//记录是否成功
					if (res.data.status == 1) {
						THIS.setData({
							getinfobutton: false,
							userInfo: {
								icon: userInfo.avatarUrl,
								nickname: userInfo.nickName
							}
						});
            // that.loginStep(THIS)
            console.log(userInfo)
						that.setWxUserInfo(userInfo);
					}
				});
				// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
				// 所以此处加入 callback 以防止这种情况
				if (this.userInfoReadyCallback) {
					this.userInfoReadyCallback(res)
				}
        var pages = getCurrentPages()
        if (pages[pages.length - 1].route.indexOf('game/color_over') != -1) {
          THIS.getAuth()
        } else {
          wx.redirectTo({
            url: that.url,
          })
        }
        // if (typeof options.jump === 'undefined' || options.jump == 'undefined' || !options.jump) {
        //   wx.redirectTo({
        //     url: '../index/index' + '?new_url=' + options.new_url
        //   });
        // } else {
        //   wx.redirectTo({
        //     url: options.jump + '?goods_id=' + options.goods_id + '&type=' + options.type + '&id=' + options.id +
        //       '&user_id=' + options.user_id + '&activity_id=' + options.activity_id + '&new_url=' + options.new_url,
        //   });
        // };
			},
		})
	},
	scene_decode: function(scene) {
		var _str = scene + "";
		var _str_list = _str.split(",");
		var res = {};
		for (var i in _str_list) {
			var _tmp_str = _str_list[i];
			var _tmp_str_list = _tmp_str.split(":");
			if (_tmp_str_list.length > 0 && _tmp_str_list[0]) {
				res[_tmp_str_list[0]] = _tmp_str_list[1] || null;
			}
		}
		return res;
	}

})
